package com.yaxin.lucene;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.hadoop.hdfs.lucene.po.NioResult;

public class HadoopLucene {

	public static void main(String[] args){
		try{
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("_class", "HdfsIndex");
			param.put("_method", "createIndex");
			param.put("param", "hdfs://192.168.0.104:9000/hdfs/test/qq.txt");
			sendToServer("192.168.0.104",11899,param,new CallBack(){
			//sendToServer("127.0.0.1",11899,param,new CallBack(){
				@Override
				public Object doCall(NioResult rs) {
					if(rs != null){
						if(rs.isSuccess()){
							System.out.println(rs.getData().get("data_host"));
						}else
							System.out.println(rs.getMsg());
					}
					return null;
				}
				
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@Deprecated
	public static void sendToServer(String ip,int port,Map<String,Object> param,String _class,String callback){
		IoConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ByteArrayCodecFactory()));  
		connector.setHandler(new ClientHandler(_class,callback));
		IoSession session = null;
		ConnectFuture future = connector.connect(new InetSocketAddress(ip, port));
		future.awaitUninterruptibly();
		session = future.getSession();
		try {
			session.write(ByteUtil.objectToByte(param));
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.close(true);
	}
	
	public static void sendToServer(String ip,int port,Map<String,Object> param,CallBack call){
		IoConnector connector = new NioSocketConnector();
		connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ByteArrayCodecFactory()));  
		connector.setHandler(new ClientHandler(call));
		IoSession session = null;
		ConnectFuture future = connector.connect(new InetSocketAddress(ip, port));
		future.awaitUninterruptibly();
		session = future.getSession();
		try {
			session.write(ByteUtil.objectToByte(param));
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(call == null){
			session.close(true);
		}
	}
}
